<?php

namespace App\Http\Controllers\Common\TagData\Video;

use App\Http\Controllers\Controller;
use App\Http\Requests\Common\TagData\Video\VcattagRequest;
use App\Jobs\Publish\VcattagJob;
use App\Models\Common\CatData\Video\Vcat;
use App\Models\Common\TagData\Video\Vcattag;
use App\Models\Task\Task;
use App\Models\Common\EntityData\Channel\Sp;
use App\Models\Common\EntityData\Channel\Ogroup;
use App\Repositories\Common\TagData\Video\VcattagRepository;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Flash;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Route;
use Response;

class VcattagController extends Controller
{
    use ModelForm;

    /** @var  VcattagRepository */
    private $vcattagRepository;

    /**
     * [$publishWhere 上线发布的条件]
     * @var array
     */
    protected $publishWhere = ['publish_status' => 0];

    /**
     * [$publishDownWhere 下线发布的条件]
     * @var array
     */
    protected $publishDownWhere = ['publish_status' => 1];

    public function __construct(VcattagRepository $vcattagRepo)
    {
        $this->vcattagRepository = $vcattagRepo;
    }

    /**
     * Display a listing of the Vcattag.
     *
     * @return Response
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header(__('common.tag_data.video.vcattags.index_header'));
            $content->description(__('common.tag_data.video.vcattags.index_description'));

            $content->body($this->grid());
        });
    }

    /**
     * Show the form for creating a new Vcattag.
     *
     * @return Response
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header(__('common.tag_data.video.vcattags.create_header'));
            $content->description(__('common.tag_data.video.vcattags.create_description'));

            $content->body($this->form());

        });
    }

    /**
     * Store a newly created Vcattag in storage.
     *
     * @param VcattagRequest $request
     *
     * @return Response
     */
    public function store(VcattagRequest $request)
    {
        $input = $request->all();

        $vcattag = $this->vcattagRepository->create($input);
        $data    = [];
        // 服务商ID 目前服务商ID是瀚动的
        $data['vcattag_id'] = $vcattag->id;
        // 分类吧编号
        $data['vcattag_no'] = $vcattag->vcattag_no;
        // 名称
        $data['name'] = $vcattag->name;
        // 标题
        $data['title'] = $vcattag->title;
        // 副标题
        $data['subtitle'] = $vcattag->subtitle;
        DB::connection('interface')->table('vcattags')->insert($data);
        Flash::success(__('common.tag_data.video.vcattags.saved_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('common.tag_data.video.vcattags.index'));

    }

    /**
     * Display the specified Vcattag.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function show($id)
    {
        $vcattag = $this->vcattagRepository->findWithoutFail($id);

        if (empty($vcattag)) {
            Flash::error(__('common.tag_data.video.vcattags.not_found'));

            return redirect(route('common.tag_data.video.vcattags.index'));
        }

        return view('common.tag_data.video.vcattags.show')->with('vcattag', $vcattag);

    }

    /**
     * Show the form for editing the specified Vcattag.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header(__('common.tag_data.video.vcattags.edit_header'));
            $content->description(__('common.tag_data.video.vcattags.edit_description'));

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Update the specified Vcattag in storage.
     *
     * @param  int              $id
     * @param VcattagRequest $request
     *
     * @return Response
     */
    public function update($id, VcattagRequest $request)
    {
        $vcattag = $this->vcattagRepository->findWithoutFail($id);

        if (empty($vcattag)) {
            Flash::error(__('common.tag_data.video.vcattags.not_found'));

            return redirect(route('common.tag_data.video.vcattags.index'));
        }

        $vcattag = $this->vcattagRepository->update($request->all(), $id);
        // 同时更新数据库
        $data               = [];
        $data['vcattag_id'] = $id;
        $data['vcattag_no'] = $request->input('vcattag_no');
        $data['name']       = $request->input('name');
        $data['title']      = $request->input('title');
        $data['subtitle']   = $request->input('subtitle');
        $interfaceVcattag   = DB::connection('interface')->table('vcattags')->where(['vcattag_id' => $id])->first();
        if ($interfaceVcattag) {
            DB::connection('interface')->table('vcattags')->where(['vcattag_id' => $id])->update($data);
        } else {
            DB::connection('interface')->table('vcattags')->insert($data);
        }
        Flash::success(__('common.tag_data.video.vcattags.updated_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('common.tag_data.video.vcattags.index'));
    }

    /**
     * Remove the specified Vcattag from storage.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        // 根据 `,` 判断传递过来的是单个id还是多个id
        if (substr_count($id, ',') >= 1) {
            $id = explode(",", $id);
        }

        // 如果是数组则进行批量删除
        if (is_array($id)) {
            if ($flag = $this->vcattagRepository->batchDelete('id', $id)) {
                DB::connection('interface')->table('vcattags')->whereIn('vcattag_id', $id)->delete();
                return response()->json(['message' => __('common.tag_data.video.vcattags.deleted_success'), 'status' => $flag]);
            } else {
                return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
            }
        }

        $vcattag = $this->vcattagRepository->findWithoutFail($id);

        if (empty($vcattag)) {
            Flash::error(__('common.tag_data.video.vcattags.not_found'));

            return redirect(route('common.tag_data.video.vcattags.index'));
        }

        if ($flag = $this->vcattagRepository->delete($id)) {
            DB::connection('interface')->table('vcattags')->where('vcattag_id', $id)->delete();
            return response()->json(['message' => __('common.tag_data.video.vcattags.deleted_success'), 'status' => $flag]);
        } else {
            return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
        }
    }

    /**
     * 根据归类选出归类下面的所有分类
     */
    public function vcattagOrEmpty(Request $request)
    {
        $vcat_id = $request->get('q');
        $data    = Vcattag::where('vcat_id', '=', $vcat_id)->get(['id', 'name'])->toArray();
        return array_merge([['id' => '', 'name' => '选择']], $data);
    }

    /**
     * 分类发布 TODO:发布状态,加入队列,发布状态过滤
     */
    public function publish(Request $request)
    {
        if (Admin::user()->cannot('common.tag_data.video.vcattags.publish')) {
            self::myinfo('您的权限不够!');
            return;
        }

        // 判断已发布的分类是否为空
        if (!Vcattag::where($this->publishWhere)->count()) {
            self::myinfo('需要上线发布的分类为空!');
            $taskid = self::insertTasks([
                'task_type' => '分类上线发布',
                'total_num' => -1,
                'user_id'   => Admin::user()->id,
            ]);
            return response()->json(['taskid' => $taskid, 'content' => '没有需要上线发布的分类!']);
        }

        // 任务表插入一条记录
        $taskid = self::insertTasks([
            'task_type' => '分类上线发布',
            'user_id'   => Admin::user()->id,
        ]);

        dispatch(new VcattagJob(1, '', $taskid));
        return response()->json(['taskid' => $taskid, 'content' => '<div width:100px;height:100px;background:red;">上线发布成功!</div>']);
    }

    /**
     * 下线发布功能
     */
    public function publishDown(Request $request)
    {
        if (Admin::user()->cannot('common.tag_data.video.vcattags.publish_down')) {
            self::myinfo('您的权限不够!');
            return;
        }
        if (!Vcattag::where($this->publishDownWhere)->count()) {
            self::myinfo('需要下线发布的分类为空!');
            $taskid = self::insertTasks([
                'task_type' => '分类下线发布',
                'total_num' => -1,
                'user_id'   => Admin::user()->id,
            ]);
            return response()->json(['taskid' => $taskid, 'content' => '没有需要下线发布的分类!']);
        }
        // 任务表插入一条记录
        $taskid = self::insertTasks([
            'task_type' => '分类下线发布',
            'user_id'   => Admin::user()->id,
        ]);
        dispatch(new VcattagJob(3, '', $taskid));
        return response()->json(['taskid' => $taskid, 'content' => '<div width:100px;height:100px;background:red;">下线发布成功!</div>']);
    }

    /**
     * 查询进度
     */
    public function queryProgress(Request $request)
    {
        $taskid = (int) $request->input('taskid');
        $data   = Task::where('id', $taskid)->first();
        if ($data->total_num === 0) {
            return response()->json(['percent' => '0%']);
        }
        if ($data->total_num === -1) {
            return response()->json(['percent' => '100%']);
        }
        return response()->json(['percent' => ceil($data->done_num * 100 / $data->total_num) . '%']);
    }

    /**
     * 获取一个任务id
     */
    public static function insertTasks($data)
    {
        try {
            return Task::insertGetId($data);
        } catch (\Exception $e) {
            dd($e->getMessage());
        }
    }

    /**
     * 提示信息
     */
    public static function myinfo($info)
    {
        Flash::success($info);
        return redirect(route('common.tag_data.video.vcattags.index'));
    }

    /**
     * [form description]
     * @return {[type]} [description]
     */
    protected function form()
    {
        return Admin::form(Vcattag::class, function (Form $form) {

            $form->display('id', 'ID');
            $form->ztree('pid', '上级分类')
                ->zTreeConfig(["map" => ["id" => "id", "title" => 'name', 'pid' => 'pId'], "type" => "radio", "open" => true])
                ->options(Vcattag::get(['id', 'pid', 'title']));
            $form->text('vcattag_no', '分类编号')->help('必填');
            $sps = Sp::pluck('name', 'id');
            $form->select('sp_id', 'SP')->options($sps);
            $ogroups = Ogroup::pluck('name', 'id');
            $form->select('ogroup_id', '渠道')->options($ogroups);
            $form->text('name', '名称')->help('必填');
            $form->text('catid', '原始分类ID');
            $form->text('title', '标题');
            $form->text('subtitle', '副标题');
            $vcats = Vcat::pluck('name', 'id');
            $form->select('vcat_id', '归类')->options($vcats);

            // $form->display('created_at', __('base.created_at'));
            // $form->display('updated_at', __('base.updated_at'));

        });
    }

    /**
     * [grid description]
     * @return {[type]} [description]
     */
    protected function grid()
    {

        return Admin::grid(Vcattag::class, function (Grid $grid) {
            // 考虑是否需要scope和排序
            // $grid->model()->orderBy('listorder', 'asc');

            // //添加按钮
            // if (!\Gate::check('common.tag_data.video.vcattags.create')) {
            //     $grid->disableCreation();
            // }

            // // 编辑和删除按钮
            // $grid->actions(function ($actions) {
            //     //编辑按钮
            //     if (!\Gate::check('common.tag_data.video.vcattags.edit')) {
            //         $actions->disableEdit();
            //     }
            //     //删除按钮
            //     if (!\Gate::check('common.tag_data.video.vcattags.destroy')) {
            //         $actions->disableDelete();
            //     }
            // });

            // //导出按钮
            // if (!\Gate::check('common.tag_data.video.vcattags.export')) {
            //     $grid->disableExport();
            // }

            // //批量操作
            // $grid->tools(function ($tools) {
            //     $tools->batch(function ($batch) {
            //         //批量删除按钮
            //         if (!\Gate::check('common.tag_data.video.vcattags.batch_destroy')) {
            //             $batch->disableDelete();
            //         }
            //     });
            // });

            //添加按钮
            if (Admin::user()->cannot('common.tag_data.video.vcattags.create')) {
                $grid->disableCreation();
            }

            // 编辑和删除按钮
            $grid->actions(function ($actions) {
                $id = $actions->getKey();
                //编辑按钮
                if (Admin::user()->cannot('common.tag_data.video.vcattags.edit')) {
                    $actions->disableEdit();
                }
                //删除按钮
                if (Admin::user()->cannot('common.tag_data.video.vcattags.destroy')) {
                    $actions->disableDelete();
                }
            });

            //导出按钮
            if (Admin::user()->cannot('common.tag_data.video.vcattags.export')) {
                $grid->disableExport();
            }

            //批量操作
            $grid->tools(function ($tools) {
                $url2 = route('common.tag_data.video.vcattags.progress');
                // // 上线发布功能
                // if (Admin::user()->can('common.tag_data.video.vcattags.publish')) {
                //     $url      = route('common.tag_data.video.vcattags.publish');
                //     $function = "upAndDownByAll('$url', '$url2', 'get')";
                //     $tools->append('<a href="javascript:void(0)" onclick="' . $function . '" class="btn btn-sm btn-success pull-right" style="margin-right: 10px"> <i class="fa fa-cloud-upload"></i>上线发布</a>');
                //     // $tools->append('<a href="' . route('common.tag_data.video.vcattags.publish') . '" class="btn btn-sm btn-info pull-right" style="margin-right: 10px"> <i class="glyphicon glyphicon-floppy-open"></i>发布</a>');
                // }

                // // 取消发布功能
                // if (Admin::user()->can('common.tag_data.video.vcattags.publish_down')) {
                //     $url      = route('common.tag_data.video.vcattags.publish_down');
                //     $function = "upAndDownByAll('$url', '$url2', 'get')";
                //     $tools->append('<a href="javascript:void(0)" onclick="' . $function . '" class="btn btn-sm btn-danger pull-right" style="margin-right: 10px"> <i class="fa fa-cloud-download"></i>下线发布</a>');
                // }
                $url =  route('entity.assets.assets.model',['sp_no' => '','config_file_select'=>'']);
                $tools->append('<a href=' .$url. ' class="btn btn-sm btn-warning pull-right" title="导入数据"><i class="fa fa-ban"></i>导入数据</a>');

                $tools->batch(function ($batch) {
                    //批量删除按钮
                    if (Admin::user()->cannot('common.tag_data.video.vcattags.batch_destroy')) {
                        $batch->disableDelete();
                    }
                });
            });

            $grid->column('id', 'ID')->sortable();
            $grid->column('vcattag_no', '分类编号')->sortable();
            $grid->column('sp.name', 'SP')->sortable();
            $grid->column('ogroup.name', '渠道')->sortable();
            $grid->column('pid', '上级分类')->display(function ($val) {
                $vcattagName = Vcattag::where('id', $val)->value('title');
                return $vcattagName ? $vcattagName : '';
            })->sortable();
            $grid->column('name', '名称')->sortable();
            $grid->column('title', '标题')->sortable();
            $grid->column('subtitle', '副标题')->sortable();
            $grid->column('vcat.name', '归类')->sortable();
            // $grid->column('publish_status', '发布状态')->display(function ($val) {
            //     switch ($val) {
            //         case 0:
            //             return '<span class="badge bg-red">未发布</span>';
            //             break;
            //         case 1:
            //             return '<span class="badge bg-green">已发布</span>';
            //             break;
            //         default:
            //             return '未知';
            //     }
            // })->sortable();

            /**
             * 过滤处理
             */
            $grid->filter(function ($filter) {
                // 禁用id查询框
                // $filter->disableIdFilter();
                // 名称
                $filter->like('name', '名称');
                // 标题
                $filter->like('title', '标题');
            });
        });
    }
}
